<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Region, Riderlist, RiderStreet, OrderProduct, Order, Graborder, Message, Coupon};
use think\Facade\Config as Configs;
use app\facade\Mns;
use think\Validate;
use think\Db;
use EasyWeChat\Factory;
use think\facade\Log;


class Rider extends Base
{
    public function login()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ], [
            'mobile.require' => '登录手机号不能为空',
            'password.require' => '登录密码不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where('mobile', $data['mobile'])->find();
        if (empty($user) || $user['password'] != md5(md5($data['password']))) {
            $this->result([], 1, '账号或密码错误');
        }
        $token = 'RIDER' . md5(md5($user['id'] . time()));
        Redis::setex($token, 86400 * 7, $user['id']);
        $this->result(['token' => $token], 0, '登录成功');
    }

    public function orderlist()
    {
        $status = $this->request->get('status/d', 1);
        $lat = $this->request->get('lat', 0) ?? 0;
        $lng = $this->request->get('lng', 0) ?? 0;
        if (empty($lat) || empty($lng)) {
            $lat = 0;
            $lng = 0;
        }
        Log::write($lat, 'getlons');
        $model = (new Order());
        $rider = $this->request->reder;
        $filed = 'ROUND(6371.004*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lng . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $list = $model->field('id,ordersn,ccount,refund,lat,lon,name,mobile,street,address,posaddress,info,status,issystem,payment,total,images1,images2,ptotal,appointment,created,' . $filed);
        switch ($status) {
            case '1':
                $street = (new RiderStreet())->distinct(true)->where(['riderid' =>  $this->request->reder_id, 'status' => 2])->column('street');
                $agents = (new RiderStreet())->distinct(true)->where(['riderid' =>  $this->request->reder_id, 'status' => 2])->column('agentid');
                $list = $list->order(['dist' => 'asc', 'appointment' => 'asc'])->where(['status' => 2, 'agentid' => $agents]);
                break;
            case '2':
                $list = $list->order(['ordertime' => 'desc'])->where(['orderid' => $rider['id'], 'status' => 3]);
                break;
            case '3':
                $list = $list->order(['endtime' => 'desc'])->where(['orderid' => $rider['id'], 'status' => 4]);
                break;
            default:
                $list = $list->where(['id' => 0]);
                break;
        }
        $list = $list->paginate(50, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $street = getdrees($lists['street'], 2);
            $lists['province_text'] = $street['province'];
            $lists['city_text'] = $street['city'];
            $lists['area_text'] = $street['area'];
            $lists['street_text'] = $street['street'];
            $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
            $lists['orderproduct'] = (new OrderProduct())->where('ordersn', $lists['ordersn'])->field('id,title,descs,images,price,number,cnumber')->select();
            $lists['status_text'] = $lists->status_text;
            $lists['payment_text'] = $lists->payment_text;
            if ($lists['dist'] < 100) {
                $lists['posaddress'] = $lists['posaddress'] . '【距你' . $lists['dist'] . '米】';
            }
            if ($lists['issystem'] == 2) {
                $lists['province_text'] = '*' . $street['province'];
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderuplon()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'lon' => 'require',
            'lat' => 'require',
        ], [
            'lon.require' => '坐标不能为空',
            'lat.require' => '坐标不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $uniques = 'orderuplon_' . $this->request->reder_id;
        $frtimes = Redis::get($uniques);
        if ($frtimes) {
            $this->result([], 1, '更新失败');
        } else {
            Redis::setex($uniques, 5, 5);
        }
        $res = (new Riderlist())->where('id', $this->request->reder_id)->update(['riderlon' => $data['lon'], 'riderlat' => $data['lat']]);
        if ($res) {
            $this->result([], 0, '更新成功');
        }
        $this->result([], 1, '更新失败');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $model = (new Order());
        $rider = $this->request->reder;
        $filed = 'ROUND(6371.004*2*ASIN(SQRT(POW(SIN((' . $rider['riderlat'] . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $rider['riderlat'] . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $rider['riderlon'] . '*PI()/180-lon*PI()/180)/2),2)))*100)/100 AS dist';
        $lists = $model->where('id', $id)->field('id,cmoney,ccount,dicttotal,ordersn,refund,lat,lon,name,mobile,street,address,posaddress,info,status,images1,images2,payment,total,ptotal,appointment,created,' . $filed)->find();
        if (empty($lists)) {
            $this->result([], 1, '获取失败');
        }
        $street = getdrees($lists['street'], 2);
        $lists['province_text'] = $street['province'];
        $lists['city_text'] = $street['city'];
        $lists['area_text'] = $street['area'];
        $lists['street_text'] = $street['street'];
        $lists['dictmoney'] = abs(round(($lists['dicttotal'] -  $lists['ptotal']), 2));
        $lists['appointment'] = !empty($lists['appointment']) ? $lists['appointment'] : '无';
        $lists['orderproduct'] = (new OrderProduct())->where('ordersn', $lists['ordersn'])->field('id,title,descs,images,price,number,cnumber')->select();
        $lists['status_text'] = $lists->status_text;
        $lists['payment_text'] = $lists->payment_text;
        $images1 = json_decode($lists['images1'] ?? '', true) ?? [];
        $images2 = json_decode($lists['images2'] ?? '', true) ?? [];
        $lists['images1'] = [];
        $lists['images2'] = [];
        if (is_array($images1)) {
            $lists['images1'] = $images1;
        }
        if (is_array($images2)) {
            $lists['images2'] = $images2;
        }
        $this->result($lists, 0, '获取成功');
    }

    public function orders()
    {
        $id = $this->request->get('id/d', 0);
        $order = (new Order())->where(['id' => $id, 'status' => 2])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或用户已取消');
        }
        //判断是否为自己街道订单
        $riderstreet = (new RiderStreet())->where(['riderid' =>  $this->request->reder_id, 'street' => $order['street'], 'status' => 2])->find();
        if (empty($riderstreet)) {
            $this->result([], 1, '无当前街道接单权限');
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id'], 'status' => 2])->update(['status' => 3, 'orderid' => $this->request->reder_id, 'ordertime' => date('Y-m-d H:i:s')]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->result([], 1, '接单失败，请重试');
        }
        $this->result([], 0, '接单成功');
    }

    public function riderstreet()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'street' => 'require'
            ], [
                'street.require' => '街道ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['lat'] = $data['lat'] ?? 0;
            $data['lng'] = $data['lng'] ?? 0;
            Log::write($data, 'getlons');
            $streets = getlatlon($data['lat'], $data['lng'], 3);
            if (empty($streets['street'])) {
                $streets = getdrees($data['street'], 3);
            }
            if (empty($streets['street']) || empty($streets['area']) || empty($streets['city']) || empty($streets['province'])) {
                $this->result([], 1, '地址信息错误，请重新选择或刷新页面重试');
            }
            //代理ID
            if (empty($streets['agentid'])) {
                $this->result([], 1, '当前街道暂未开放申请');
            }
            $riderid = $this->request->reder_id;
            $haverider = (new RiderStreet())->where(['riderid' => $riderid, 'status' => [1, 2]])->value('agentid') ?? 0;
            if (!empty($haverider) && $streets['agentid'] != $haverider) {
                $this->result([], 1, '此街道与您已申请街道不属于同一管理人员,无法申请');
            }
            $riderstreet = (new RiderStreet())->where(['riderid' => $riderid, 'street' => $streets['street']])->find();
            if (!empty($riderstreet) && $riderstreet['status'] == 1) {
                $this->result([], 1, '当前街道已在审核中，请等待审核');
            }
            if (!empty($riderstreet) && $riderstreet['status'] == 2) {
                $this->result([], 1, '您已有当前街道权限,无需重复申请');
            }
            //保存数据
            $addstreet = [
                'riderid' => $riderid,
                'agentid' => $streets['agentid'] ?? 0,
                'province' => $streets['province'],
                'city' => $streets['city'],
                'area' => $streets['area'],
                'street' => $streets['street'],
                'status' => 1,
                'lat' => $data['lat'],
                'lon' => $data['lng']
            ];
            Db::startTrans();
            try {
                if (empty($riderstreet)) {
                    (new RiderStreet())->allowfield(true)->save($addstreet);
                } else {
                    (new RiderStreet())->allowfield(true)->save($addstreet, ['id' => $riderstreet['id']]);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '申请失败，请重试');
            }
            $this->result([], 0, '申请成功，待审核');
        } else {
            $list = (new RiderStreet())->field('street,area,status')->where(['riderid' => $this->request->reder_id])->select();
            foreach ($list as $lists) {
                $address = getdrees($lists['street'], 2);
                $lists['province_text'] = $address['province'];
                $lists['city_text'] = $address['city'];
                $lists['area_text'] = $address['area'];
                $lists['street_text'] = $address['street'];
            }
            $this->result($list, 0, '获取成功');
        }
    }

    public function  message()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'message' => 'require',
                'type' => 'require|in:1,2,3',
            ], [
                'message.require' => '反馈内容为空',
                'type.require' => '反馈类型不能为空',
                'type.in' => '反馈类型不正确',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $data['messtype'] = $data['type'];
            $data['type'] = 2;
            $data['user_id'] = $this->request->reder_id;
            if (!empty($data['images'])) {
                $images = json_decode($data['images'] ?? '', true) ?? [];
                if (is_array($images) && count($images) > 0) {
                    $data['images'] = json_encode($images, true);
                } else {
                    $data['images'] = '';
                }
            } else {
                $data['images'] = '';
            }
            $res = (new Message())->allowfield(true)->save($data);
            if ($res) {
                $this->result([], 0, '提交成功');
            }
            $this->result([], 1, '提交失败');
        } else {
            $list = (new Message())->order('id desc');
            $list = $list->where(['user_id' =>  $this->request->reder_id, 'type' => 2])
                ->field('message,reply,mobile,created,images,messtype,type')
                ->paginate(20, false, ['query' => $this->request->param()])->each(function ($item) use ($list) {
                    $item['images'] = json_decode($item['images'], true) ?? [];
                    $item['type_text'] = $item->type_text;
                    return $item;
                });
            $this->result($list, 0, '查询完成');
        }
    }

    public function  returnorder()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'mobile' =>  'require',
            ], [
                'id.require' => '订单ID不能为空',
                'mobile.require' => '转让人账号不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            //查看订单是否存在
            $order = (new Order())->where(['id' => $data['id'], 'status' => 3, 'orderid' => $this->request->reder_id])->find();
            if (empty($order)) {
                $this->result([], 1, '订单不可转让');
            }
            if ($data['mobile'] == $this->request->reder['mobile']) {
                $this->result([], 1, '订单不可以转让给自己');
            }
            $user = (new Riderlist())->where(['mobile' => $data['mobile']])->find();
            if (empty($user) || $user['status'] != 1) {
                $this->result([], 1, '转让人不存在或处于不在线状态');
            }
            //判断用户是否存在或有没有接单权限
            $RiderStreet = (new RiderStreet())->where(['riderid' => $user['id'], 'status' => 2])->find();
            if (empty($RiderStreet)) {
                $this->result([], 1, '该骑手无订单所属街道接单权限');
            }
            Db::startTrans();
            try {
                (new Order())->where(['id' => $order['id'], 'status' => 3])->update(['orderid' => $user['id']]);
                (new Graborder())->insert(['user_id' => $user['id'], 'comeuser_id' => $this->request->reder_id, 'orderid' => $order['id'], 'type' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result([], 1, '转让失败，请重试');
            }
            $this->result([], 0, '转让成功');
        }
    }

    public function confirmorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' =>  'require|in:4,5',
        ], [
            'id.require' => '订单id不能为空',
            'status.require' => '操作状态不能为空',
            'status.in' => '操作状态类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id'], 'orderid' => $this->request->reder_id, 'status' => 3])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或不可操作');
        }
        $user = (new Users())->where('id', $order['user_id'])->find();
        $endtime = date('Y-m-d H:i:s');
        $caceltime = date('Y-m-d H:i:s');
        $data['images2'] = $order['images2'];
        if ($data['status'] == 4) {
            if (!empty($data['images'])) {
                if (!is_array($data['images'])) {
                    $images = json_decode($data['images'] ?? '', true) ?? [];
                } else {
                    $images = $data['images'];
                }
                if (is_array($images) && count($images) > 0) {
                    $data['images2'] = json_encode($images, true);
                } else {
                    $this->result([], 1, '照片上传出错,请重试或刷新页面');
                }
            } else {
                $this->result([], 1, '请上传清洗后照片');
            }
            $endtime = date('Y-m-d H:i:s');
            $caceltime = $order['caceltime'];
        }
        if ($data['status'] == 5) {
            $endtime = $order['endtime'];
            $caceltime = date('Y-m-d H:i:s');
        }
        $msg = '操作成功';
        $data['refund'] = 1;
        if ($data['status'] == 5 && $order['total'] > 0 && $order['payment'] > 1) {
            $data['refund'] = 2;
            $msg = "操作成功，退款将原路返回";
        }
        $coupon = json_decode($order['coupons'], true) ?? [];
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id'], 'status' => 3])->update([
                'refund' => $data['refund'],
                'status' => $data['status'],
                'endtime' => $endtime,
                'caceltime' => $caceltime,
                'images2' => $data['images2']
            ]);
            //积分赠送
            if ($data['status'] == 4 && !empty($user)) {
                (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 1, $order['id'], '下单赠送');
            }
            if ($data['status'] == 5 && $order['coupon'] > 0) {
                (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
            }
            if ($data['status'] == 5 && count($coupon) > 0) {
                (new Coupon())->where(['id' => $coupon])->update(['status' => 1]);
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, $msg);
    }

    public function orderupload()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'images' =>  'require',
        ], [
            'id.require' => '订单id不能为空',
            'images.require' => '照片不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where(['id' => $data['id'], 'orderid' => $this->request->reder_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在或不可操作');
        }
        if (!is_array($data['images'])) {
            $images = json_decode($data['images'] ?? '', true) ?? [];
        } else {
            $images = $data['images'];
        }
        if (is_array($images) && count($images) > 0) {
            $data['images1'] = json_encode($images, true);
        } else {
            $this->result([], 1, '照片上传出错,请重试或刷新页面');
        }
        Db::startTrans();
        try {
            (new Order())->where(['id' => $order['id']])->update([
                'images1' => $data['images1']
            ]);
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败，请重试');
        }
        $this->result([], 0, '操作成功');
    }

    public function getstatus()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'status' => 'require|in:1,2,3'
        ], [
            'status.require' => '状态类型不能为空',
            'status.in' => '状态类型错误'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $user = (new Riderlist())->where(['id' => $this->request->reder_id])->find();
        if ($user['status'] == $data['status']) {
            $this->result([], 1, '状态未更改');
        }
        $res = (new Riderlist())->where(['id' => $this->request->reder_id])->update(['status' => $data['status']]);
        if ($res) {
            $this->result([], 0, '更改成功');
        }
        $this->result([], 1, '更改失败，请重试');
    }

    public function getinfo()
    {

        $user = (new Riderlist())->field('id,mobile,name,cards,status,openid')->where(['id' => $this->request->reder_id])->find();
        $user['isgz'] = 1;
        if (empty($user['openid'])) {
            $user['isgz'] = 2;
        }
        $this->result($user, 0, '获取成功');
    }
}
